# -*- coding: utf-8 -*-
"""
@Time    : 2024/8/8 14:17 
@Author  : ZhangShenao 
@File    : 1.抛出与捕获异常.py 
@Desc    : 抛出与捕获异常

使用Flask内置的abort函数,可以抛出特定状态码的异常
"""

from flask import Flask, request, abort, Response

app = Flask(__name__)
app.config['DEBUG'] = True


@app.route("/", methods=["GET"])
def index() -> str:
    # 校验token,如果不合法,则通过abort函数抛出异常,拒绝访问
    token = request.headers.get("X-TOKEN")
    if token is None or token != "123456":
        response = Response(response="请先登录", status=401)
        abort(code=response)

    # print(1 / 0)  # 模拟异常
    return "欢迎回来~"


@app.errorhandler(ZeroDivisionError)
def error_handler(error):
    """定义异常处理器,捕获特定异常"""
    return {"error": f"{error}"}


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
